// Copyright (c) Appeon. All rights reserved.
// Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. 
// You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0.

using System;
using System.IO;
using System.Text;

namespace SnapObjects.Data
{
    /// <summary>
    ///     Defines a data template, for exporting data from the JSON or XML format.
    /// </summary>
    public class DataTemplate : IDataTemplate
    {
        private string _content;

        public DataTemplate()
        {
            this.MetadataProvider = new TemplateExportMetadataProvider();
        }

        public DataTemplate(string filePath) : this(filePath, Encoding.UTF8)
        {
        }

        public DataTemplate(string filePath, Encoding encoding) : this()
        {
            this.LoadFile(filePath, encoding);
        }

        /// <summary>
        ///     Gets the file path of the data template.
        /// </summary>
        public string FilePath { get; private set; }

        public DataFormat DataFormat { get; private set; }

        /// <summary>
        ///     Gets the content of the data template.
        /// </summary>
        public string Content
        {
            get => _content;

            private set
            {
                _content = value;

                this.DataFormat = this.GetFormat(_content);
            }
        }

        internal ITemplateExportMetadataProvider MetadataProvider { get; }

        /// <summary>
        ///     Loads the template from a file.
        /// </summary>
        /// <param name="filePath">The path of the file.</param>
        public void LoadFile(string filePath)
        {
            this.LoadFile(filePath, Encoding.UTF8);
        }

        /// <summary>
        ///     Loads the template from a file and specifies the encoding for the content.
        /// </summary>
        /// <param name="filePath">The path of the file.</param>
        /// <param name="encoding">The encoding applied to the contents of the file.</param>
        public void LoadFile(string filePath, Encoding encoding)
        {
            filePath = this.FixFilePath(filePath);

            if (!Path.IsPathRooted(filePath))
            {
                filePath = Path.Combine(AppContext.BaseDirectory, filePath);
            }

            if (File.Exists(filePath))
            {
                this.Content = File.ReadAllText(filePath, encoding);
                this.FilePath = filePath;
            }
            else
            {
                throw new FileNotFoundException(filePath);
            }
        }

        /// <summary>
        ///     Loads the template from a string.
        /// </summary>
        /// <param name="content">he content of the template.</param>
        public void LoadContent(string content)
        {
            this.Content = content;
            this.FilePath = String.Empty;
        }

        /// <summary>
        ///     Sets parameter values for the XML template.
        /// </summary>
        /// <param name="name">The name of the placeholder in the template.</param>
        /// <param name="value">The value to be assigned to the placeholder in the template.</param>
        public void SetParameter(string name, object value)
        {
            this.MetadataProvider.AddParameter(name, value);
        }

        private DataFormat GetFormat(string template)
        {
            var dataFormat = DataFormat.Text;

            if (!String.IsNullOrWhiteSpace(template))
            {
                var content = template.TrimStart();

                var firstChar = content[0];

                if (firstChar == '{' || firstChar == '[')
                {
                    dataFormat = DataFormat.Json;
                }
                else
                {
                    dataFormat = DataFormat.Xml;
                }
            }

            return dataFormat;
        }

        private string FixFilePath(string path)
        {
            if (String.IsNullOrWhiteSpace(path))
            {
                return path;
            }

            if (Path.DirectorySeparatorChar == '\\')
            {
                return path.Replace('/', '\\');
            }

            if (Path.DirectorySeparatorChar == '/')
            {
                return path.Replace('\\', '/');
            }

            throw new NotSupportedException();
        }
    }
}
